<template>
	<view class="">
		<view class="bg sticky top-0" style="z-index: 2;">
			<view class="all-header">
				<view :style="{height:statusBarHeight}" class="bg"></view>
				<view class="h-44p flex justify-center items-center bg" @click="type?type=0:type=1">
					<text class="text-17">{{type?'收入':'支出'}}</text><text class="iconfont icon-arrow-down ml-4"></text>
				</view>
			</view>
			<view class="flex justify-around tabTitle p-24">
				<text :class="{active:current==0}" @click="onDateTypeChange(0)">周</text>
				<text :class="{active:current==1}" style="border-left: none;border-right: none;" @click="onDateTypeChange(1)">月</text>
				<text :class="{active:current==2}" @click="onDateTypeChange(2)">年</text>
			</view>
			<scroll-view v-if="current==0" class="scroll-view_H" scroll-x="true" :scroll-left="80*weekOrder">
				<view v-for="i in weekOrder" :key="i" :id="'time'+i" class="scroll-view-item_H" :class="{'active':weekActive==i}" @click="onWeekChange(i)">
					<text>{{i==weekOrder?'本周':i==weekOrder-1?'上周':yearArr[yearActive]+'-'+i}}</text>
				</view>
			</scroll-view>
			<scroll-view v-else-if="current==1" class="scroll-view_H" scroll-x="true" :scroll-left="80*curMon">
				<view v-for="i in curMon" :key="i" :id="'time'+i" class="scroll-view-item_H" :class="{'active':monActive==i}" @click="onMonChange(i)">
					<text>{{i==curMon?'本月':i==curMon-1?'上月':yearArr[yearActive]+'-'+i}}</text>
				</view>
			</scroll-view>
			<scroll-view v-else class="scroll-view_H" scroll-x="true" :scroll-left="80*yearArr.length">
				<view v-for="(item,i) in yearArr" :key="i" :id="'time'+i" class="scroll-view-item_H" :class="{'active':yearActive==i}" @click="onYearChange(i)">
					<text>{{i==yearArr.length-1?'今年':i==yearArr.length-2?'上年':item}}</text>
				</view>
			</scroll-view>
			
		</view>
		<view class="flex flex-column px-20 pt-20 pb-10 bg-white">
			<text class="mb-6 text-666">总{{type?'收入':'支出'}}:&nbsp;&nbsp;{{getTotal}}元</text>
			<text class="text-14 text-666">{{current==0||current==1?'日':'月'}}平均值:&nbsp;&nbsp;{{getAverage}}元</text>
		</view>
		<view class="charts-box bg-white">
			<qiun-data-charts  type="line"
			  :opts="opts"
			  :chartData="chartData"
			   :ontouch="true"/>
		</view>
		 <view class="charts-box bg-white" v-if="pieChartData?.series?pieChartData?.series[0].data.length>0:false">
		    <qiun-data-charts 
		      type="pie"
		      :opts="pieOpts"
		      :chartData="pieChartData"
		    />
			
		  </view>
		<!-- <view style="background-color: #eee;height: 20px;"></view> -->
		<!-- 支出/收入排行榜 -->
		<view class="flex flex-column px-20 pb-24 bg-white">
			<view class="pt-20 pb-10 bg-white sticky" style="z-index: 3; top: 199px;">
				<text class="mb-10">{{type?'收入':'支出'}}排行榜</text>
			</view>
			<template v-if="list.length>0">
				<view v-for="(item,index) in list" class="flex items-center" style="border-bottom: 2px dashed #eee;" @click="go(item.type_id,item.title)">
					<text class="iconfont bg p-16r mr-20r" :class="item.icon"  style="font-size: 30px; border-radius:50%;"></text>
					<view class="flex-auto flex flex-column py-20">
						<view class="flex">
							<text>{{item.title}}&nbsp;&nbsp;<text class="text-14 text-666">{{item.rate}}</text></text>
							
						</view>
						<view style="background-color: #eee;" class="rounded-3">
							<view class="bg h-6p rounded-3" :style="{width:item.rate}"></view>
						</view>
					</view>
					<view class="flex items-center">
						<view class="flex flex-column items-end ml-10">
							<text class="text-333 mb-6">￥{{formatMoney(item.num)}}</text>
							<text class="text-666 text-12">{{item.count}}笔</text>
						</view>
						<text class="iconfont icon-arrow-right ml-6 text-333"></text>
					</view>
				</view>
			</template>
			<view v-else class="empty flex-auto flex flex-column justify-center items-center">
				<text class="iconfont icon-wushuju"></text>
				<text>暂无数据</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {getRank,getLine,getAllYear} from '@/api/api.js';
	import {formatMoney} from '@/common/format.js'
	import {getWeekOrder,getWeekXAxis,getDaysInMon} from '@/common/statistic.js'
	export default {
		data() {
			return {
				type:0,
				current: 0,
				weekActive:0,
				weekOrder:null,
				curYear:null,
				yearArr:[],
				yearActive:null,
				curMon:null,
				monActive:null,
				curDate:null,
				curDay:null,
				dateValue:null,
				list:[],
				chartData: {},
				  //您可以通过修改 config-ucharts.js 文件中下标为 ['line'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				opts: {
					color: ["orange"],
					padding: [15,10,10,10],
					enableScroll: true,
					legend:{
						show:false
					},
					xAxis: {
					  disableGrid: true,
					  scrollShow: true,
					  itemCount: 7,
					  scrollAlign:this.current==2?parseInt(this.curMon)<=6?'left':'right':'left',
					  // labelCount:14
					},
					yAxis:{
					  gridType: "dash",
					  dashLength: 10,
					  showTitle:true,
					  data:[
						  {
							  title:"元",
							  titleOffsetX:-10
						  }
					  ]
					},
					extra:{
						 markLine: {
							 type:'dash',
							 dashLength: 12,
							data: [
								{
									value: 0,
									showLabel: true,
									labelOffsetX:6,
									// labelOffsetY:-10,
									// labelPadding: 2,
									labelBgColor:'#fffae8',
									labelFontColor:'#DE4A42',
								}
							]
						}
					}
				},
				
				pieChartData: {},
				pieOpts: {
					color: ["#EE6666","#FC8452","#3CA272",'#5470c6',"#FAC858","#91CB74","#1890FF","#9A60B4","#73C0DE","#ea7ccc","#D5D581"],
					padding: [8,5,5,5],
					enableScroll: false,
					extra: {
					  pie: {
						activeOpacity: 0.5,
						activeRadius: 10,
						offsetAngle: 0,
						labelWidth: 15,
						// border: false,
						borderWidth: 1,
						borderColor: "#fff"
					  }
					}
				}
			}
		},
		computed: {
			weekOrderParam() {
				return this.weekActive.toString().padStart(2,'0')
			},
			monOrderParam() {
				return this.monActive.toString().padStart(2,'0')
			},
			getTotal() {
				let sum = 0
				if(!this.chartData.series) {
					return sum
				}
				for (let num of this.chartData.series[0]?.data) {
					sum += num
				}
				return sum?.toFixed(2)
			},
			getAverage() {
				return (this.getTotal / (this.current==0?7:this.current==1?this.daysInMon:12)).toFixed(2);
			},
			statusBarHeight() {
				return (uni.getSystemInfoSync()).statusBarHeight +'px'
			},
			daysInMon() {
				return getDaysInMon()
			},
		},
		watch: {
			type() {
				this.getData()
			},
			getAverage(val) {
				this.opts.extra.markLine.data[0].value = Number(val)
			}
		},
		async onPullDownRefresh() {
			// console.log('refresh')
			await this.getData()
			uni.stopPullDownRefresh();
		},
		async onLoad() {
			const date = new Date()
			this.curYear = date.getFullYear().toString()
			this.curMon = (date.getMonth()+1)
			this.monActive = this.curMon
			this.curDate =this.curMon.toString().padStart(2,'0') +'-'+date.getDate().toString().padStart(2,'0');
			this.curDay = date.getDay()
			this.weekOrder = getWeekOrder()
			this.weekActive = this.weekOrder
			const yearArr = await getAllYear()
			if(yearArr.indexOf(this.curYear)==-1) {
				yearArr.push(this.curYear)
				this.yearActive = yearArr.length - 1
			} else {
				this.yearActive = yearArr.indexOf(this.curYear)
			}
			this.yearArr = yearArr
			
			this.dateValue = this.yearArr[this.yearActive]+'-'+ this.weekOrderParam
			await this.getData()
		},
		methods: {
			go(id,title) {
				uni.navigateTo({
					url:'/pages/chart/rankDetail?type_id='+id+'&type_title='+title+'&date_type='+this.current+'&date_value='+this.dateValue+'&type='+this.type
				})
			},
			onDateTypeChange(val) {
				this.current = val
				switch (val){
					case 0:
					this.weekActive = this.weekOrder
					this.dateValue =this.yearArr[this.yearActive]+'-'+ this.weekOrderParam
					
						break;
					case 1:
					this.monActive = this.curMon
						this.dateValue =this.yearArr[this.yearActive]+'-'+ this.monOrderParam
						
						break;
					case 2:
					this.yearActive = this.yearArr.length -1
						this.dateValue = this.yearArr[this.yearActive]
						break;
				}
				this.getData()
			},
			onWeekChange(i) {
				this.weekActive=i
				this.dateValue = this.yearArr[this.yearActive]+'-'+ this.weekOrderParam
				this.getData()
			},
			onMonChange(i) {
				this.monActive = i
				this.dateValue = this.yearArr[this.yearActive]+'-'+ this.monOrderParam
				this.getData()
			},
			onYearChange(i) {
				this.yearActive = i
				this.dateValue = this.yearArr[i]
				this.getData()
			},
			formatMoney(num) {
				return formatMoney(num)
			},
			async getData() {
				// 获取折线图
				await this.getLineChart()
				// 获取金额排行列表
				await this.getRankList()
				// 获取饼图
				this.getPieChart()
			},
			async getLineChart() {
				const list = await getLine(this.type,this.current,this.dateValue)
				// console.log(JSON.stringify(list))
				const date = new Date()
				// const week = getWeekXAxis(date)
				const data = [],month = [],mon_date=[],
						week = ['1','2','3','4','5','6','0'],
						weekTxt = ['一','二','三','四','五','六','日']
				for(let i=1;i<=12;i++) {
					month.push(i.toString().padStart(2,'0'))
				}
				for(let i=1;i<=getDaysInMon();i++) {
					// mon_date.push(this.curMon.toString().padStart(2,'0')+'-'+i.toString().padStart(2,'0'))
					mon_date.push(i.toString().padStart(2,'0'))
				}
				let categories = [];
				
				if(this.current==0) {
					for (let index of week) {
						data.push((list.filter(item => item.week == index))[0]?.num ?? 0)
					}
					if(this.weekActive==this.weekOrder) {
						categories = week.map((val,index) => val==this.curDay ? '今天' :'周'+ weekTxt[index])
					} else {
						categories = week.map((val,index) => '周'+weekTxt[index] )
					}
					this.opts.xAxis.scrollShow = false
				}
				if(this.current==1) {
					for (let date of mon_date) {
						data.push((list.filter(item => item.date.split('-')[1] == date))[0]?.num ?? 0)
					}
					if(this.monActive==this.curMon) {
						categories = mon_date.map((val) =>this.curMon.toString().padStart(2,'0')+'-'+ val==this.curDate ? '今天 ' :val)
					} else {
						categories = mon_date.map((val) => val)
					}
				}
				if(this.current==2) {
					for (let mon of month) {
						data.push((list.filter(item => item.mon == mon))[0]?.num ?? 0)
					}
					if(this.yearActive==this.yearArr.length - 1) {
					categories = month.map((val) => val==this.curMon ? '本月 ' :val)
					} else {
					categories = month
					}
					// this.opts.xAxis.scrollShow = true
					// this.opts.xAxis.itemCount = 6
				}
				// console.log(data)
				let res = {
					categories,
					series: [
					  {
						name: "金额",
						data
					  },
					]
				  };
				this.chartData = JSON.parse(JSON.stringify(res));
			},
			async getRankList() {
			
				const rankList = await getRank(this.type,this.current,this.dateValue);
				let sum = 0
				for (let item of rankList) {
					sum+= item.num
				}
				this.list = rankList.map(item => {
					item.rate = (item.num / sum * 100).toFixed(2)+'%'
					return item
				})
			
				// console.log(this.list)
			},
			getPieChart() {
				// 支出分类
				const dimission = [{
					name:'食品酒水',
					idArr:[1,5,6,7],
					value:0
				},{
					name:'衣服饰品',
					idArr:[10,11],
					value:0
				},{
					name:'行车交通',
					idArr:[4,17],
					value:0
				},{
					name:'居家物业',
					idArr:[3,12,13,22],
					value:0
				},{
					name:'休闲娱乐',
					idArr:[8,9,14,15],
					value:0
				},{
					name:'学习进修',
					idArr:[19,21],
					value:0
				},{
					name:'人情往来',
					idArr:[20,23],
					value:0
				},{
					name:'数码',
					idArr:[16],
					value:0
				},{
					name:'购物',
					idArr:[2,24],
					value:0
				},{
					name:'医疗',
					idArr:[18],
					value:0
				}];
				let data = [];
				if(this.type) {//收入
					data = this.list.map(item => {
						return {
							name:item.title,
							value:item.num
						}
					})
				} else {//支出
					for (let item of this.list) {
						if(item.icon=='icon-owner_set') {//自定义类型
							dimission.push({
								name:item.title,
								value:item.num
							})
						} else {
							for(let i=0;i<dimission.length -1;i++) {
								if(!dimission[i].idArr) {
									continue;
								}
								if(dimission[i].idArr.includes(item.type_id)) {
									dimission[i].value += item.num
								}
							}
						}
					}
					data = dimission.filter(item => item.value > 0).sort((a,b) => {
						a=a['value'];
						b=b['value'];
						if(a<b){ return 1}
						if(a>b){ return -1 }
						return 0
					})
				}
				let res = {
				            series: [
				              {
				                data
				              }
				            ]
				          };
				        this.pieChartData = JSON.parse(JSON.stringify(res));
			}
		}
	}
</script>

<style scoped lang="scss">
	
	.active {
		color: white;
		background-color: #000;
	}
	.tabTitle {
		background-color: gold;
		text {
			flex-basis: 50%;
			text-align: center;
			padding: 12rpx 0;
			border: 1px solid #000;
		}
	}
	.scroll-view_H {
			white-space: nowrap;
			width: 100%;
		}
		.scroll-view-item_H {
				display: inline-block;
				// width: 100%;
				height: 30px;
				line-height: 30px;
				text-align: center;
				font-size: 32rpx;
				padding: 0 10px;
			}
	.charts-box {
		width: 100%;
		height: 350rpx;
	}	
	.empty {
		color: #ccc;
		.iconfont {
			font-size: 60px;
			margin-bottom: 10px;
		}
	}
</style>

